
package com.example.android.commitcontent.ime.service;

import android.content.Intent;
import android.inputmethodservice.InputMethodService;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.android.commitcontent.ime.R;
import com.example.android.commitcontent.ime.activities.FeedbackActivity;
import com.example.android.commitcontent.ime.beans.HanZiCharacter;
import com.example.android.commitcontent.ime.beans.PinYinCharacter;
import com.example.android.commitcontent.ime.cores.adapters.BaseRecyclerViewAdapter;
import com.example.android.commitcontent.ime.cores.adapters.BaseSingleChooseAdapter;
import com.example.android.commitcontent.ime.database.hanzi.HanZiStatisticsDataBaseHelper;
import com.example.android.commitcontent.ime.dict.HanZiDictHelper;
import com.example.android.commitcontent.ime.keyboard.adapters.PinYinSideListAdapter;
import com.example.android.commitcontent.ime.keyboard.adapters.PinYinWordsSuggestionAdapter;
import com.example.android.commitcontent.ime.keyboard.adapters.SymbolAdapter;
import com.example.android.commitcontent.ime.keyboard.adapters.SymbolCategoryAdapter;
import com.example.android.commitcontent.ime.keyboard.data.KeyboardData;
import com.example.android.commitcontent.ime.keyboard.enums.KeyboardType;
import com.example.android.commitcontent.ime.keyboard.event_handler.BackspaceKyeEventHandler;
import com.example.android.commitcontent.ime.keyboard.event_handler.MoreKeysHandler;
import com.example.android.commitcontent.ime.keyboard.managers.PinYinCombination;
import com.example.android.commitcontent.ime.keyboard.managers.PinYinWordsBuilder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.BindViews;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 键盘服务
 */
public class PinYinIME extends InputMethodService implements MoreKeysHandler.OnPinYinCharacterSelectedListener, PinYinCombination.PinYinCombinationListener {

    //键盘根布局
    private View mKeyboardView;

    //当前键盘类型
    private KeyboardType mCurrentKeyboardType;
    //历史键盘记录
    private List<KeyboardType> mKeyboardHistoryList = new ArrayList<>();

    //所有键盘布局
    @BindViews({R.id.ll_pinyin_keyboard_container, R.id.ll_english_keyboard_container, R.id.ll_digit_keyboard_container, R.id.ll_symbol_keyboard_container})
    List<ViewGroup> mKeyboardContainerList;
    @BindView(R.id.ll_pinyin_keyboard_container)
    LinearLayout mLlPinyinKeyboardContainer;
    @BindView(R.id.ll_english_keyboard_container)
    LinearLayout mLlEnglishKeyboardContainer;
    @BindView(R.id.ll_digit_keyboard_container)
    LinearLayout mLlDigitKeyboardContainer;
    @BindView(R.id.ll_symbol_keyboard_container)
    LinearLayout mLlSymbolKeyboardContainer;

    //拼音键盘工具栏
    @BindView(R.id.ll_pinyin_toolbar)
    LinearLayout mLlPinyinToolbar;
    //拼音键盘候选词列表
    @BindView(R.id.rv_pinyin_words_suggestion)
    RecyclerView mRvPinYinWordsSuggestion;
    //拼音键盘候选词列表（筛选）
    @BindView(R.id.rv_pinyin_words_suggestion_from_filter)
    RecyclerView mRvPinYinWordsSuggestionFromFilter;
    //拼音键盘符号列表
    @BindView(R.id.rv_pinyin_symbol)
    RecyclerView mRvPinYinSymbol;
    //拼音组合建议列表
    @BindView(R.id.rv_pinyin_suggestion)
    RecyclerView mRvPinYinSuggestion;
    //拼音组合建议列表（筛选）
    @BindView(R.id.rv_pinyin_suggestion_from_filter)
    RecyclerView mRvPinYinSuggestionFromFilter;
    //拼音组合建议列表数据
    List<String> mPinYinCombineList = new ArrayList<>();
    List<String> mPinYinSuggestionList = new ArrayList<>();

    //拼音组合类
    private PinYinCombination mPinYinCombination;
    //拼音候选词适配器
    private PinYinWordsSuggestionAdapter mPinYinWordsSuggestionAdapter;
    private PinYinWordsSuggestionAdapter mPinYinWordsSuggestionAdapterFromFilter;
    //拼音组合建议列表adapter
    private PinYinSideListAdapter mPinYinSuggestionAdapter;
    //拼音组合建议列表adapter（筛选）
    private PinYinSideListAdapter mPinYinSuggestionAdapterFromFilter;
    //拼音候选列表数据
    private List<HanZiCharacter> mPinYinWordsSuggestionList = new ArrayList<>();
    //拼音候选列表数据（笔顺筛选后）
    private List<HanZiCharacter> mPinYinWordsSuggestionListFiltered = new ArrayList<>();
    //拼音键盘View集合
    @BindViews({R.id.row1_btn1, R.id.row1_btn2, R.id.row1_btn3, R.id.row1_btn4, R.id.row1_btn5,
            R.id.row2_btn1, R.id.row2_btn2, R.id.row2_btn3, R.id.row2_btn4, R.id.row2_btn5,
            R.id.row3_btn1, R.id.row3_btn2, R.id.row3_btn3, R.id.row3_btn4, R.id.row3_btn5,})
    List<View> mPinYinKeyList;

    //拼音串提示
    private TextView candidateView;

    //拼音结果 笔顺筛选条件标记，1横  2竖  3撇  4点  5折
    private int mBiShunFilterFlag = 0;

    @Override
    public void onCreate() {
        super.onCreate();
        // TODO: Avoid file I/O in the main thread.
//        final File imagesDir = new File(getFilesDir(), "images");
//        imagesDir.mkdirs();
        new Thread() {
            @Override
            public synchronized void start() {
                //todo load database data into memory
//                HanZiDictHelper.loadDatabaseHanZiToMemory(PinYinIME.this);
            }
        }.start();
    }

    @BindViews({R.id.iv_english_backspace, R.id.iv_digit_backspace, R.id.iv_symbol_backspace, R.id.iv_pinyin_backspace, R.id.iv_bishun_filter_backspace})
    List<View> mBackspaceList;
    @BindViews({R.id.iv_pinyin_enter, R.id.iv_english_enter, R.id.iv_digit_enter})
    List<ImageView> mEnterKeyImageViewList;

    @Override
    public View onCreateInputView() {
        mKeyboardView = LayoutInflater.from(this).inflate(R.layout.layout_keyboard_frame, null);
        ButterKnife.bind(this, mKeyboardView);
        init();
        initPinYinKeyboard();
        initEnglishKeyboard();
        initDigitKeyboard();
        initSymbolKeyboard();
        for (View view : mBackspaceList)
            view.setOnTouchListener(new BackspaceKyeEventHandler(this::backspace));
        return mKeyboardView;
    }

    private void init() {
        //指定当前键盘类型
        mCurrentKeyboardType = KeyboardType.PinyinKeyboard;
        //拼音组合类、注册监听
        mPinYinCombination = PinYinCombination.instance();
        mPinYinCombination.register(this);
        HanZiStatisticsDataBaseHelper.intance(this);
    }

    /**
     * 初始化拼音键盘
     */
    private void initPinYinKeyboard() {
        mPinYinWordsSuggestionAdapter = new PinYinWordsSuggestionAdapter(this, R.layout.item_suggestion_word, mPinYinWordsSuggestionListFiltered);
        mPinYinWordsSuggestionAdapter.setOnWordItemClickListener(new PinYinWordsSuggestionAdapter.OnWordItemClickListener() {
            @Override
            public void onWordItemClick(int position, HanZiCharacter hanZiCharacter) {
                commitText(hanZiCharacter.hanzi);
                mPinYinWordsBuilder.append(hanZiCharacter);
                if (hanZiCharacter.isWord()) {
                    mPinYinCombination.clear();
                } else {
                    HanZiStatisticsDataBaseHelper.intance(PinYinIME.this).repeatCount(hanZiCharacter);
                    mPinYinCombination.removeFirstPinYin();
                }
            }
        });
        mRvPinYinWordsSuggestion.setAdapter(mPinYinWordsSuggestionAdapter);
        mRvPinYinWordsSuggestion.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));

        mPinYinWordsSuggestionAdapterFromFilter = new PinYinWordsSuggestionAdapter(this, R.layout.item_suggestion_word_from_filter, mPinYinWordsSuggestionListFiltered);
        mPinYinWordsSuggestionAdapterFromFilter.setOnWordItemClickListener(new PinYinWordsSuggestionAdapter.OnWordItemClickListener() {
            @Override
            public void onWordItemClick(int position, HanZiCharacter hanZiCharacter) {
                commitText(hanZiCharacter.hanzi);
                mPinYinWordsBuilder.append(hanZiCharacter);
                if (hanZiCharacter.isWord()) {
                    mPinYinCombination.clear();
                } else {
                    HanZiStatisticsDataBaseHelper.intance(PinYinIME.this).repeatCount(hanZiCharacter);
                    mPinYinCombination.removeFirstPinYin();
                }
            }
        });
        mRvPinYinWordsSuggestionFromFilter.setAdapter(mPinYinWordsSuggestionAdapterFromFilter);
        mRvPinYinWordsSuggestionFromFilter.setLayoutManager(new GridLayoutManager(this, 4));

        for (int i = 0; i < mPinYinKeyList.size(); i++) {
            mPinYinKeyList.get(i).setOnTouchListener(new MoreKeysHandler(this, KeyboardData.PinYin.pinYinCharacterList[i], this));
        }


        mRvPinYinSymbol.setLayoutManager(new LinearLayoutManager(this));
        mRvPinYinSymbol.setAdapter(new PinYinSideListAdapter(this, R.layout.item_pinyin_side_list, KeyboardData.PinYin.symbolList) {
            @Override
            protected void onHolderCreated(@NonNull Holder holder) {
                holder.itemView.setOnClickListener(view -> commitText(getDataList().get(holder.getAdapterPosition())));
            }
        });

        mRvPinYinSuggestion.setLayoutManager(new LinearLayoutManager(this));
        mPinYinSuggestionAdapter = new PinYinSideListAdapter(this, R.layout.item_pinyin_side_list, mPinYinSuggestionList) {
            @Override
            protected void onHolderCreated(@NonNull Holder holder) {
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
//                        commitText(getDataList().get(holder.getAdapterPosition()));
                        mPinYinCombination.replaceFirstPinYin(getDataList().get(holder.getAdapterPosition()));
                    }
                });
            }

//            @Override
//            public int getItemCount() {
//                return getDataList().size() > 0 ? 1 : 0;
//            }
        };
        mRvPinYinSuggestion.setAdapter(mPinYinSuggestionAdapter);

        mRvPinYinSuggestionFromFilter.setLayoutManager(new LinearLayoutManager(this));
        mPinYinSuggestionAdapterFromFilter = new PinYinSideListAdapter(this, R.layout.item_pinyin_side_list, mPinYinSuggestionList) {
            @Override
            protected void onHolderCreated(@NonNull Holder holder) {
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
//                        commitText(getDataList().get(holder.getAdapterPosition()));
                        mPinYinCombination.replaceFirstPinYin(getDataList().get(holder.getAdapterPosition()));
                    }
                });
            }

//            @Override
//            public int getItemCount() {
//                return getDataList().size() > 0 ? 1 : 0;
//            }
        };
        mRvPinYinSuggestionFromFilter.setAdapter(mPinYinSuggestionAdapterFromFilter);
    }

    /**
     * 初始化英文键盘
     */
    private void initEnglishKeyboard() {
        LinearLayout en_key_container = (LinearLayout) mKeyboardView.findViewById(R.id.ll_en_key_container);
        CharacterKeyEventHandler keyEventHandler = new CharacterKeyEventHandler();
        for (int i = 0; i < en_key_container.getChildCount(); i++) {
            View child = en_key_container.getChildAt(i);
            if (child instanceof LinearLayout) {
                LinearLayout linearLayout = (LinearLayout) child;
                for (int i1 = 0; i1 < linearLayout.getChildCount(); i1++) {
                    View c = linearLayout.getChildAt(i1);
                    if (c.getTag() != null && c.getTag().equals("alphabet")) {
                        c.setOnClickListener(keyEventHandler);
                        TextView textView = ((TextView) ((ViewGroup) c).getChildAt(1));
                        alphabetKeyList.add(textView);
                    }
                }
            }
        }
    }

    class CharacterKeyEventHandler implements View.OnClickListener {
        @Override
        public void onClick(View view) {
            commitText(((TextView) ((ViewGroup) view).getChildAt(1)).getText());
        }
    }

    @BindView(R.id.ll_digit_number_container)
    LinearLayout mLlDigitNumberContainer;

    /**
     * 初始化数字键盘
     */
    private void initDigitKeyboard() {
        //digit keyboard
        RecyclerView rvDigitSymbol = (RecyclerView) mKeyboardView.findViewById(R.id.rv_digit_symbol);
        rvDigitSymbol.setLayoutManager(new LinearLayoutManager(this));
        rvDigitSymbol.setAdapter(new PinYinSideListAdapter(this, R.layout.item_pinyin_side_list, KeyboardData.Digit.symbolList) {
            @Override
            protected void onHolderCreated(@NonNull Holder holder) {
                holder.itemView.setOnClickListener(view -> commitText(getDataList().get(holder.getAdapterPosition())));
            }
        });
        for (int i = 0; i < mLlDigitNumberContainer.getChildCount(); i++) {
            View childAt = mLlDigitNumberContainer.getChildAt(i);
            if (childAt instanceof ViewGroup) {
                for (int i1 = 0; i1 < ((ViewGroup) childAt).getChildCount(); i1++) {
                    View view = ((ViewGroup) childAt).getChildAt(i1);
                    if (view.getTag() != null && view.getTag().equals("number"))
                        view.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                commitText(((TextView) view).getText());
                            }
                        });
                }
            }
        }
    }

    /**
     * 初始化符号键盘
     */
    private void initSymbolKeyboard() {
        RecyclerView rvSymbolCategory = (RecyclerView) mKeyboardView.findViewById(R.id.rv_symbol_category);
        RecyclerView rvSymbol = (RecyclerView) mKeyboardView.findViewById(R.id.rv_symbol);
        ArrayList<String> symbolCategoryList = new ArrayList<>();
        symbolCategoryList.add(getString(R.string.str_chinese));
        symbolCategoryList.add(getString(R.string.str_english));
        symbolCategoryList.add(getString(R.string.str_pinyin));
        symbolCategoryList.add(getString(R.string.str_math));
        SymbolCategoryAdapter symbolCategoryAdapter = new SymbolCategoryAdapter(this, R.layout.item_symbol_category, symbolCategoryList, -1, 0);
        rvSymbolCategory.setAdapter(symbolCategoryAdapter);
        rvSymbolCategory.setLayoutManager(new LinearLayoutManager(this));
        symbolCategoryAdapter.setOnItemSelectedListener(new BaseSingleChooseAdapter.OnItemSelectedListener() {
            @Override
            public void onItemSelected(int position) {
                symbol_list.clear();
                symbol_list.addAll(KeyboardData.Symbol.allSymbolList.get(position));
                symbolAdapter.notifyDataSetChanged();
                rvSymbol.scrollToPosition(0);
            }

            @Override
            public void onItemReselected(int position) {

            }
        });

        symbol_list.addAll(KeyboardData.Symbol.allSymbolList.get(0));
        symbolAdapter = new SymbolAdapter(this, R.layout.item_symbol, symbol_list);
        symbolAdapter.setOnItemClickListener(new BaseRecyclerViewAdapter.OnItemClickListener<String>() {
            @Override
            public void onItemClick(String data, int position) {
                commitText(data);
            }
        });
        rvSymbol.setAdapter(symbolAdapter);
        rvSymbol.setLayoutManager(new GridLayoutManager(this, 4));
    }

    @Override
    public void onPinYinCharacterSelected(PinYinCharacter pinYinCharacter, int position) {
        mPinYinCombination.addPinYinCharacter(pinYinCharacter);
    }

    @Override
    public void onPinYinCombinationGenerated(List<String> combinationList, String candidateText, List<String> pinyinSuggestionList) {
        mPinYinCombineList.clear();
        mPinYinSuggestionList.clear();
        if (combinationList.size() > 0)
            mPinYinCombineList.addAll(combinationList);
        if (pinyinSuggestionList.size() > 0)
            mPinYinSuggestionList.addAll(pinyinSuggestionList);
        mPinYinSuggestionAdapter.notifyDataSetChanged();
        mPinYinSuggestionAdapterFromFilter.notifyDataSetChanged();
        clearBiShunFilterFlag();
        candidateView.setText(candidateText);
        updatePinYinViewsDisplayState();
    }

    private PinYinWordsBuilder mPinYinWordsBuilder = PinYinWordsBuilder.instance();

    /**
     * 更新拼音相关控件状态
     */
    private void updatePinYinViewsDisplayState() {
        mPinYinWordsSuggestionList.clear();
        mPinYinWordsSuggestionListFiltered.clear();
        if (mPinYinCombineList.size() > 0) {
            mRvPinYinSymbol.setVisibility(View.GONE);
            mRvPinYinSuggestion.setVisibility(View.VISIBLE);
            mLlPinyinToolbar.setVisibility(View.GONE);
            mPinYinWordsSuggestionList.addAll(HanZiDictHelper.queryHanZiCharactersByPinYin(mPinYinCombineList));
            mPinYinWordsSuggestionListFiltered.addAll(mPinYinWordsSuggestionList);
            setCandidatesViewShown(true);
        } else {
            mRvPinYinSuggestion.setVisibility(View.GONE);
            mLlContainerCNFilter.setVisibility(View.GONE);
            mRvPinYinSymbol.setVisibility(View.VISIBLE);
            mLlPinyinToolbar.setVisibility(View.VISIBLE);
            setCandidatesViewShown(false);
            if (mPinYinWordsBuilder.length() > 0) {
                mPinYinWordsBuilder.buildNewWord();
            }
        }
        mPinYinWordsSuggestionAdapter.notifyDataSetChanged();
        mPinYinWordsSuggestionAdapterFromFilter.notifyDataSetChanged();
        mRvPinYinWordsSuggestion.scrollToPosition(0);
        mRvPinYinWordsSuggestionFromFilter.scrollToPosition(0);
    }

    /**
     * 当拼音组合被清空
     */
    @Override
    public void onCombinationCleared() {
        updatePinYinViewsDisplayState();
    }


    /**
     * 创建拼音提示视图
     *
     * @return
     */
    @Override
    public View onCreateCandidatesView() {
        FrameLayout frameLayout = (FrameLayout) LayoutInflater.from(this).inflate(R.layout.layout_candidate_view, null);
        candidateView = (TextView) frameLayout.getChildAt(0);
        return frameLayout;
    }


    @BindViews({R.id.tv_pinyin_send, R.id.tv_english_send, R.id.tv_digit_send})
    List<TextView> mTvSendList;


    /**
     * 切换键盘
     *
     * @param keyboardType
     */
    private void switchKeyboard(KeyboardType keyboardType) {
        mKeyboardHistoryList.add(mCurrentKeyboardType);
        mCurrentKeyboardType = keyboardType;
        hideAllKeyboards();
        showKeyboard(keyboardType);
    }

    @OnClick(R.id.iv_show_bihua_filter)
    void iv_show_bihua_filter() {
        mLlContainerCNFilter.setVisibility(View.VISIBLE);
    }

    /**
     * 隐藏所有键盘
     */
    private void hideAllKeyboards() {
        for (ViewGroup viewGroup : mKeyboardContainerList) {
            viewGroup.setVisibility(View.GONE);
        }
        setCandidatesViewShown(false);
    }

    /**
     * 显示指定的键盘
     *
     * @param keyboardType
     */
    private void showKeyboard(KeyboardType keyboardType) {
        switch (keyboardType) {
            case PinyinKeyboard:
                updatePinYinViewsDisplayState();
                mLlPinyinKeyboardContainer.setVisibility(View.VISIBLE);
                break;
            case EnglishKeyboard:
                mLlEnglishKeyboardContainer.setVisibility(View.VISIBLE);
                break;
            case DigitKeyBoard:
                mLlDigitKeyboardContainer.setVisibility(View.VISIBLE);
                break;
            case SymbolKeyboard:
                mLlSymbolKeyboardContainer.setVisibility(View.VISIBLE);
                break;
        }
    }


    List<TextView> alphabetKeyList = new ArrayList<>();

    @BindView(R.id.iv_english_caps_lock)
    ImageView mIvCapsLock;

    /**
     * 关闭软键盘
     */
    @OnClick({R.id.iv_english_close_keyboard, R.id.iv_pinyin_close_keyboard, R.id.iv_digit_close_keyboard, R.id.iv_symbol_close_keyboard})
    void closeKeyboard() {
        requestHideSelf(0);
    }

    /**
     * 切换到符号键盘
     */
    @OnClick({R.id.tv_digit_switch_to_symbol, R.id.tv_english_switch_to_symbol, R.id.tv_pinyin_switch_to_symbol})
    void switchToSymbolKeyboard() {
        switchKeyboard(KeyboardType.SymbolKeyboard);
    }

    /**
     * 切换到数字键盘
     */
    @OnClick({R.id.tv_english_switch_to_digit, R.id.tv_pinyin_switch_to_digit})
    void switchToDigitKeyboard() {
        switchKeyboard(KeyboardType.DigitKeyBoard);
    }

    /**
     * 切换到英文键盘
     */
    @OnClick({R.id.tv_pinyin_switch_to_english})
    void switchToEnglishKeyboard() {
        switchKeyboard(KeyboardType.EnglishKeyboard);
    }

    /**
     * 切换到中文键盘
     */
    @OnClick(R.id.ll_english_switch_to_pinyin)
    void switchToPinYin() {
        switchKeyboard(KeyboardType.PinyinKeyboard);
    }

    /**
     * 返回上一次使用的键盘
     */
    @OnClick({R.id.tv_symbol_back_to_last_keyboard, R.id.tv_digit_back_to_last_keyboard})
    void backToLastKeyboard() {
        mCurrentKeyboardType = mKeyboardHistoryList.remove(mKeyboardHistoryList.size() - 1);
        hideAllKeyboards();
        showKeyboard(mCurrentKeyboardType);
    }


    /**
     * 提交文字到输入框
     *
     * @param charSequence
     */
    void commitText(CharSequence charSequence) {
        getCurrentInputConnection().commitText(charSequence, 0);
    }

    @OnClick(R.id.iv_close_bi_hua_filter)
    void iv_close_bi_hua_filter() {
        mLlContainerCNFilter.setVisibility(View.GONE);
    }

    /**
     * 英文大写锁定
     */
    @OnClick(R.id.iv_english_caps_lock)
    void iv_english_caps_lock() {
        if (alphabetKeyList.size() == 0) return;
        String text = alphabetKeyList.get(0).getText().toString();
        boolean isToLowerCase = false;
        if ((text.charAt(0)) <= 90) {
            isToLowerCase = true;
        }
        mIvCapsLock.setImageResource(isToLowerCase ? R.mipmap.ic_shift_off : R.mipmap.ic_shift_on);
        for (TextView textView : alphabetKeyList) {
            String s = textView.getText().toString();
            textView.setText(isToLowerCase ? s.toLowerCase() : s.toUpperCase());
        }
    }

    List<String> symbol_list = new ArrayList<>();
    SymbolAdapter symbolAdapter;

    /**
     * 空格键
     */
    @OnClick({R.id.tv_pinyin_space, R.id.fl_english_space, R.id.fl_digit_space})
    void space() {
        commitText(" ");
    }

    /**
     * 退格键
     */
//    @OnClick({R.id.iv_english_backspace, R.id.iv_digit_backspace, R.id.iv_symbol_backspace, R.id.iv_pinyin_backspace, R.id.iv_bishun_filter_backspace})
    void backspace() {
        if (mCurrentKeyboardType == KeyboardType.PinyinKeyboard) {
            clearBiShunFilterFlag();
            if (mPinYinCombination.canBackspace()) {
                mPinYinCombination.backspace();
                mPinYinWordsBuilder.clear();
                return;
            }
        }
        getCurrentInputConnection().deleteSurroundingText(1, 0);
    }


    /**
     * 清空
     */
    @OnClick(R.id.tv_pinyin_clear_all)
    void clearAll() {
//      if (mCurrentKeyboardType)
        if (mPinYinCombination.canBackspace())
            mPinYinCombination.clear();
        else
            getCurrentInputConnection().deleteSurroundingText(Integer.MAX_VALUE, Integer.MAX_VALUE);
    }

    /**
     * 发送
     */
    @OnClick({R.id.fl_pinyin_send, R.id.fl_english_send, R.id.fl_digit_send})
    void send() {
        if (isEnter)
            linefeed();
        else
            getCurrentInputConnection().performEditorAction(getCurrentInputEditorInfo().actionId);
    }

    /**
     * 意见
     */
    @OnClick({R.id.tv_pinyin_feedback})
    void feedback() {
//      FeedbackActivity.startWithNewTask(getApplication());
        Intent intent = new Intent(getBaseContext(), FeedbackActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

//        Intent intent = new Intent(Settings.ACTION_INPUT_METHOD_SETTINGS);
////        intent.addFlags();
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    /**
     * 换行
     */
    @OnClick(R.id.tv_pinyin_linefeed)
    void linefeed() {
//      commitText("\n");
        getCurrentInputConnection().sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, 66));
    }

    /**
     * 输入英文' . '
     */
    @OnClick({R.id.tv_digit_dot, R.id.tv_english_dot})
    void dot() {
        commitText(".");
    }

    /**
     * 输入英文' @ '
     */
    @OnClick(R.id.tv_digit_at)
    void at() {
        commitText("@");
    }

    @BindView(R.id.ll_container_cn_filter)
    LinearLayout mLlContainerCNFilter;

//        拼音结果筛选条件标记，1横  2竖  3撇  4点  5折

    /**
     * 笔顺筛选1：一
     */
    @OnClick({R.id.row4_btn1, R.id.tv_filter_heng})
    void bishun_filter_heng() {
        setBiShunFilterFlag(1);
    }

    /**
     * 笔顺筛选2：丨
     */
    @OnClick({R.id.row4_btn2, R.id.tv_filter_shu})
    void bishun_filter_shu() {
        setBiShunFilterFlag(2);

    }

    /**
     * 笔顺筛选3：丿
     */
    @OnClick({R.id.row4_btn3, R.id.tv_filter_pie})
    void bishun_filter_pie() {
        setBiShunFilterFlag(3);
    }

    /**
     * 笔顺筛选4：丶
     */
    @OnClick({R.id.row4_btn4, R.id.tv_filter_dian})
    void bishun_filter_dian() {
        setBiShunFilterFlag(4);
    }

    /**
     * 笔顺筛选5：乛
     */
    @OnClick({R.id.row4_btn5, R.id.tv_filter_zhe})
    void bishun_filter_zhe() {
        setBiShunFilterFlag(5);
    }

    /**
     * 分词
     */
    @OnClick(R.id.tv_pinyin_split_symbol)
    void splitSymbol() {
        mPinYinCombination.addPinYinCharacter(new PinYinCharacter());
    }

    /**
     * 对当前显示的候选字结果进行笔顺筛选
     *
     * @param bishun
     */
    private void setBiShunFilterFlag(int bishun) {
        mBiShunFilterFlag = bishun;
        mPinYinWordsSuggestionListFiltered.clear();
        for (HanZiCharacter hanZiCharacter : mPinYinWordsSuggestionList) {
            if ((!TextUtils.isEmpty(hanZiCharacter.bishun)) && hanZiCharacter.bishun.startsWith(String.valueOf(bishun)))
                mPinYinWordsSuggestionListFiltered.add(hanZiCharacter);
        }
        mPinYinWordsSuggestionAdapter.notifyDataSetChanged();
        mPinYinWordsSuggestionAdapterFromFilter.notifyDataSetChanged();
        mRvPinYinWordsSuggestion.scrollToPosition(0);
        mRvPinYinWordsSuggestionFromFilter.scrollToPosition(0);
    }

    /**
     * 候选字清除笔顺筛选
     */
    private void clearBiShunFilterFlag() {
        mBiShunFilterFlag = 0;
        if (mPinYinWordsSuggestionList.size() == mPinYinWordsSuggestionListFiltered.size()) return;
        mPinYinWordsSuggestionListFiltered.clear();
        mPinYinWordsSuggestionListFiltered.addAll(mPinYinWordsSuggestionList);
        mPinYinWordsSuggestionAdapter.notifyDataSetChanged();
        mPinYinWordsSuggestionAdapterFromFilter.notifyDataSetChanged();
    }


    @Override
    public void onFinishInputView(boolean finishingInput) {
        super.onFinishInputView(finishingInput);
        mKeyboardHistoryList.clear();
        mPinYinCombination.clear();
        //检查词库更新
        CheckWordsDictUpdateService.start(this);
    }

    @Override
    public boolean onEvaluateFullscreenMode() {
        // In full-screen mode the inserted content is likely to be hidden by the IME. Hence in this
        // sample we simply disable full-screen mode.
        return false;
    }

    @Override
    public void onStartInputView(EditorInfo info, boolean restarting) {
        switchKeyboard(KeyboardType.PinyinKeyboard);
        setupSendButtons(info);
    }

    boolean isEnter;

    @BindView(R.id.iv_pinyin_enter)
    ImageView mIvPinYinCenter;

    private void setupSendButtons(EditorInfo info) {
        isEnter = false;
        String label = "";
        switch (info.imeOptions) {
            case EditorInfo.IME_ACTION_DONE:
                label = "完成";
                break;
            case EditorInfo.IME_ACTION_NEXT:
                label = "下一个";
                break;
            case EditorInfo.IME_ACTION_PREVIOUS:
                label = "上一个";
                break;
            case EditorInfo.IME_ACTION_SEND:
                label = "发送";
                break;
            case EditorInfo.IME_ACTION_SEARCH:
                label = "搜索";
                break;
            default:
                isEnter = true;
        }
        for (TextView textView : mTvSendList) {
            textView.setText(label);
        }
        for (ImageView imageView : mEnterKeyImageViewList) {
            imageView.setVisibility(isEnter ? View.VISIBLE : View.GONE);
        }
    }
}
